﻿import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text ,ScrollView,RichText} from '@tarojs/components'
import '../../assets/common.scss'
import './chat.scss'
import CommonJs from '../../utils/common'
import ChatList from './chatlist'
import Hearder from '../index/hearder'

export default class Index extends Component {
	constructor(props) {
    super(props);
    var list={
        result:[]
    }
    this.state = {
      list:list,//聊天历史记录
      qun_date:{},
      InputValue:'',
      scrollviewid:'',
      navindex:1,
      pageheight:0,
      qid:Taro.getStorageSync('dateinfo').qid,
      chatlogId:0,
      userid:Taro.getStorageSync('dateinfo').userid,
      imglist:[],
      send:true,//是否点击发送防止点击多次  多次发送
      isload:0,
      myTime:null,
      myTime1:null,
      focus:false,
      rels:2,
      hand:1,
      press:2,
      byfrom:0,
      iszy:0,
    }
  }
  config = {
    navigationBarTitleText: '加载中' 
  }
  componentWillMount () {
  	var _this=this 
    const query = Taro.createSelectorQuery()
	query.select('.qun-bgbanner').boundingClientRect( rec => {
	    Taro.getSystemInfo({ 
		  success:function(res){
	        _this.setState({
	            pageheight:res.windowHeight-rec.height
	        })
		  } 
		})
	}).exec()
  	
    var byfrom=this.$router.preload.byfrom;
    if(byfrom=="guwen"){
    	this.setState({
            byfrom:1,
            qid:this.$router.preload.friendId
        })
    	
    }
    else{
    	_this.getquninfo()
    }
    setTimeout(function(){
    	_this.getChatHistory();
    },300)
  }
  componentWillUnmount () {
    clearTimeout(this.state.myTime)
  }
  open(url,type){
  	this.$preload({
  		type:type
  	}) 
  	CommonJs.open(url);
  }

  getquninfo(){
      var date1={id:this.state.qid}
      var _this=this;
      // console.log(this.state.qid+'//111')
      CommonJs.ajaxRequest('/cluster/getEntityAndLoginId',date1,'GET',function(res){
      // console.log(JSON.stringify(res)+'//22')
      _this.setState({
        qun_date: res.content
      })
    })
  }
 
  getChatHistory(direction){
    var _this=this
  	//获取群聊天历史记录
  	if(_this.state.byfrom==1){
  		Taro.setNavigationBarTitle({title:_this.$router.preload.name})
	 	var url="/friendlog/getMoreChatlog";
	 	var dates={
	  	  friendId:_this.state.qid,
	  	  sortColumns:'id desc',
	  	  pageNumber:1,
	  	  pageSize:10,
	  	}
  	}
  	else{
	  	var dates={
	  	  clusterId:_this.state.qid,
	  	  pageNumber:1,
	  	  sortColumns:'id desc',
	  	  pageSize:10,
	      //chatRoomTypeId:_this.$router.preload.chatRoomTypeId
	  	}
	 	Taro.setNavigationBarTitle({title:'社群聊天'})
	 	var url="/clusterlog/getChatlogOrNotLogin";
	}
  	if(direction=='top'){
  		/*向上拉*/
  		var list=this.state.list;
  		dates.firstId=list.result[0].chatlogId
  	}
  	CommonJs.ajaxRequest(url,dates,'GET',function(res){
  		
  		var red=_this.state.list;
  		var fx="srcollbottom";
  		if(res.result.length>0){
			red=res;
			var arr=red.result;
			if(direction=='top'){
				var arr1=arr.reverse();
				var listred=_this.state.list.result;
				var lastid=listred[listred.length-1].chatlogId;
				red.result=arr1.concat(listred); 
				fx="srcollbottom2"
			}
			else{
				var lastid=res.result[0].chatlogId;
				red.result=arr.reverse();
			}
  			_this.setState({
	          list: red,
	          chatlogId:lastid,
	          scrollviewid:fx
	        })
  		}
  		if(direction!='top'){
	    	setTimeout(() => { _this.getchat() }, 2000)
		}
  		_this.setState({
	      isload:1
	    })
  	})
	
  } 
  	getls(){
  		
   		this.getChatHistory("top");
   	}
    getchat(){
    	//隔1秒获取是否有新信息
      var _this=this
    	var ret=_this.state
    	var lastId=ret.chatlogId
    	if(_this.state.byfrom==1){
    		var url="/friendlog/getMoreChatlog";
    		var dates={
	  			friendId:ret.qid,
		  	  	lastId:lastId
		  	}
    	}
    	else{
	    	var dates={
	  			clusterId:ret.qid,
		  	  	lastId:lastId,
	          //chatRoomTypeId:_this.$router.preload.chatRoomTypeId
		  	}
	    	var url="/clusterlog/getChatlogOrNotLogin";
    	}
	  	CommonJs.ajaxRequest(url,dates,'GET',function(res){
	        if (res) {
	          if(res.result.length>0){
	            var red=ret.list
	            for(var i=0;i<res.result.length;i++){
	              red.result.push(res.result[i])
	            }
	            var vid=_this.state.scrollviewid
	            if(vid=="srcollbottom1"){
	              vid="srcollbottom"
	            }
	            else{
	              vid="srcollbottom1"
	            }
	            _this.setState({
	              list: red,
	              chatlogId:res.result[res.result.length-1].chatlogId,
	              scrollviewid:vid
	            })
	            _this.state.myTime = setTimeout(() => { _this.getchat() }, 1000)
	          } 
	          else {
	           _this.state.myTime = setTimeout(() => { _this.getchat() }, 1000)
	          }
	        } 
	        else {
	         _this.state.myTime = setTimeout(() => { _this.getchat() }, 1000)
	        }
	        
	  	},'noloading','','hideLoad')
    }
    mysend(event){
      // console.log(event.target.value.note+'4444')
        // console.log(this.state.InputValue+"0000000000000000000000000000000000000000")
        var msg=this.state.InputValue
        // var msg = event.target.value.note
        // this.setState({
        //   InputValue:msg
        // })
        // if(msg){
        var _this = this
        var send = _this.state.send
        if(send){
            let msgs = msg
            _this.setState({
               send: false 
            })
            var userid=Taro.getStorageSync('dateinfo').userid
            var d=userid+Date.parse(new Date())+parseInt(10000*Math.random());
            //判断是否包含表情
            var regRule = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g 
            if (msgs.match(regRule)) { 
              // msgs = msgs.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, '')
              Taro.showToast({
                title:'不支持表情发送',
                icon: 'none',
                duration: 2000
              })
              _this.setState({
                send: true,
                InputValue:'',
                hand: 1
              })
            } else {
              if(_this.state.byfrom==1){
              	var url="/friendlog/chat";
              	var dates={
	              toId:_this.state.qid,
	              content:msgs,
	              fp:d
	            }
              }
              else{
	              var dates={
	                  clusterId:_this.state.qid,
	                  content:msgs,
	                  fp:d,
	                  //chatRoomTypeId:_this.$router.preload.chatRoomTypeId
	              }
	              var url="/clusterlog/chat";
	          }
           
              CommonJs.ajaxRequest(url,dates,'GET',function(res){
                  _this.setState({
                    InputValue:'',
                    send: true,
                    hand: 1
                  })
              })
            } 
          }
        
    }
    opendetails(url,id){
      this.$preload('pagename',id);
      CommonJs.openTo(url);
    }
    handleimgs(data){
        var src = []
        src.push(data)
        this.setState({
          imglist: src
        })

    }
    closes(){
      this.setState({
        imglist:[]
      })
    }
    addto(){
//    Taro.showToast({
//      title:'暂不支持此功能',
//      icon: 'none',
//      duration: 2000
//    })

	    CommonJs.openTo('/pages/info/info');
    }
    voice(event){
      // Taro.showToast({
      //   title:'暂不支持此功能',
      //   icon: 'none',
      //   duration: 2000
      // })
      // return
      // console.log(JSON.stringify(event)+'4444')
      let rels = event.target.dataset.rel
      if (rels === 2) {
        this.setState({
          focus:false,
          rels:1,
          hand:1
        })
      } else {
        let hand = null
        if (this.state.InputValue === ''){
          hand = 1
        } else {
          hand = 2
        }
        this.setState({
          focus:true,
          rels:2,
          hand:hand
        })
      }
    }
    handleGetInputValue = (event) => {
      // console.log(event.target.value+'4444')
	    // this.setState({
	    //   InputValue : event.target.value
	    // })
      if (event.target.value === '') {
        this.setState({
          hand:1,
          InputValue : event.target.value
        })
      } else {
        this.setState({
          hand:2,
          InputValue : event.target.value
        })
      } 
	 }
   apress(){
    // console.log("已经按下了222222222222222222222222222222222222222222222222222222")
    this.setState({
      press:1
    })
    const recorderManager = Taro.getRecorderManager()
    const options = {
      duration: 120000,
      numberOfChannels: 1,
      format: 'mp3'
    }
    recorderManager.start(options)
   }
   spress(){
    this.setState({
      press:2
    })
    // console.log("已经已经松开222222222222222222222222222222222222222222222222222222")
    const recorderManager = Taro.getRecorderManager()
    recorderManager.stop()
    recorderManager.onStop((res) => {
      //console.log('recorder stop'+JSON.stringify(res)+'111111111111111222')
      let tempFilePath = res.tempFilePath
      let duration = res.duration
      this.yuyinSend(tempFilePath,duration)
    })
   }
   yuyinSend(tempFilePath,duration){
    let _this = this
    let url = CommonJs.geturl()+'/upload/uploadchatfile'
    let filePath = tempFilePath
    let name = 'file'
    let formData = {}
    // console.log(url)
    CommonJs.uploadFile(url, filePath, name, formData, function(res){
      //数据转化成JSON对象（返回数据为JSON字符串）
      let json = res.replace(/\ufeff/g, '')
      let dates = JSON.parse(json)
      //毫秒转化成秒
      let second = (duration % (1000 * 60)) / 1000
      let seconds = second.toFixed(0)
      //console.log(JSON.stringify(dates)+'////res'+seconds)
      if (dates.code != 300) {
        let msg = dates.msg+'|||yuyin|||'+seconds
        _this.chats(msg)
      } else {
        Taro.showToast({
          title:'换根手指再试一次',
          icon: 'none',
          duration: 1500
        })
      }
    })
   }
   chats(msg){
    var _this = this
    var userid=Taro.getStorageSync('dateinfo').userid
    var d=userid+Date.parse(new Date())+parseInt(10000*Math.random())
	if(_this.state.byfrom==1){
	  	var url="/friendlog/chat";
	  	var dates={
	      toId:_this.state.qid,
	      content:msg,
	      fp:d
	    }
	}
	else{
	    var dates={
	      clusterId:_this.state.qid,
	      content:msg,
	      fp:d,
	      chatRoomTypeId:_this.$router.preload.chatRoomTypeId
	    }
	    var url="/clusterlog/chat";
	}
	if(msg.indexOf('yhq')>=0){
		dates.sendType=14
	}
    // console.log(JSON.stringify(dates)+'222222222222222222222222222222222222')
    CommonJs.ajaxRequest(url,dates,'GET',function(res){
      // console.log(JSON.stringify(res)+'1111111111111111111111111111111111111最后')
    })
   }
   
  render () {
    //onClick={this.mysend}
    const states = this.state.list
    const qun_date = this.state.qun_date
    const list_date = this.state.qun_date
    return (
    	<View className='page'>
        <View className='bigimg-box' style={this.state.imglist.length>0?'display:block':'display:none'}> 
           <Swiper
              className='bigimg'
              circular
              indicatorDots>
              {this.state.imglist.map((item, index) => ( 
              <SwiperItem>
                <View className='swiper'><Image mode='widthFix' src={item}  onClick={this.closes}></Image></View>
              </SwiperItem>
              ))}
            </Swiper>
        </View>
        <View className='qun-bgbanner'>
          <Hearder propItem={list_date} porpNav={this.state.navindex} propGuite={this.state.iszy} onHandOpen={this.open.bind(this)}></Hearder>
        </View>
        
	      <ScrollView className='scrollview' scrollY='true' onScrollToUpper={this.getls.bind(this)}  scrollIntoView={this.state.scrollviewid} style={'height:'+this.state.pageheight+'px'}>
		      <View className='qun-chat' style={this.state.isload==1?'display:block':'display:none'}>
		      		{states.result.map((item, index) => (
		      		  <View className={item.id==this.state.userid?'qun-chat-li mysend':'qun-chat-li friendsend'}>
				  			<Text className='chat-time'>{CommonJs.FormatDate(item.createAt,3)}</Text>
				  			<View className='qun-chat-content'>
								<View className='user-ico'>
									<Image className='user-img' mode='scaleToFill' src={item.photo?item.photo:'https://minichat.g2ma.com/kedouimg/A6984900727459logo.png'} onClick={this.opendetails.bind(this,'/pages/persinfo/persinfo',item.id)}></Image>
								</View>
								<View className='chatting-box'>
									<Text className='user-name'>{item.nickName}</Text>
									<ChatList propItem={item} onHandleImg={this.handleimgs.bind(this)}></ChatList>
								</View>
				  			</View>
				  		</View>
		      		))}
			   </View>
			   <View id='srcollbottom'></View>
			   <View id='srcollbottom1'></View>
	         <View className='qun-yysd' style={this.state.press === 2 ? 'display:none' : 'display:block'}>
	          <View className='qun-yynf'>
	            <View className='qun-ynfk'>
	              <Image className='qun-ynimg' mode='widthFix' src='https://minichat.g2ma.com/kedouimg/jh.gif'></Image>
	            </View>
	           </View>
	         </View>
		    </ScrollView>
    		<View className='send-box'>
      		<View className='send-input'>
            <Image className='keyimg' mode='scaleToFill' src={this.state.rels === 1 ? 'https://minichat.g2ma.com/kedouimg/key2.png' : 'https://minichat.g2ma.com/kedouimg/key1.png'} dataRel={this.state.rels} onClick={this.voice.bind(this)}></Image>
            <View className={this.state.press === 2 ? 'qun-ynwnz border4' : 'qun-ynwnz border3'}>
              <Input type='text' name='note' style={this.state.rels === 1 ? 'display:none' : 'display:block'} cursorSpacing='10px' focus={this.state.focus} placeholder='输入发送内容' onInput={this.handleGetInputValue.bind(this)} value={this.state.InputValue}/>
              <Button className={this.state.press === 2 ? 'qun-yuyn border2' : 'qun-yuyn border1'} style={this.state.rels === 1 ? 'display:block' : 'display:none'} onTouchstart={this.apress.bind(this)} onTouchend={this.spress.bind(this)}>{this.state.press === 2 ? '按住   说话' : '松开   结束'}</Button>
            </View>
      			<Button className='send-btn' style={this.state.hand === 1 ? 'display:none' : 'display:block'} onClick={this.mysend.bind(this)}>发送</Button>
            <View className='qunxnsn' style={this.state.hand === 1 ? 'display:block' : 'display:none'}>
              <View className='qun-xntu'>
                <Image className='keyimg' mode='scaleToFill' src='https://minichat.g2ma.com/kedouimg/add1.png' onClick={this.addto.bind(this)}></Image>
              </View>
            </View>
      		</View>
    		</View>
      </View>
    )
  }
}

